from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    """
    用户配置文件模型，扩展Django内置的User模型
    """
    user = models.OneToOneField(User, verbose_name=_('用户'), on_delete=models.CASCADE, related_name='profile')
    bio = models.TextField(_('个人简介'), max_length=500, blank=True)
    website = models.URLField(_('个人网站'), max_length=200, blank=True)
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)
    
    class Meta:
        verbose_name = _('用户资料')
        verbose_name_plural = _('用户资料')
    
    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    """当创建用户时自动创建关联的配置文件"""
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    """当保存用户时自动保存关联的配置文件"""
    instance.profile.save()
